/**
 * IpPortSpliter.java
 */
package com.mht2017.common.utils;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author yutong.xiao
 * @date 2017年8月10日 上午10:33:33
 */
public class IpPortSpliter {

	private static final Logger LOGGER = LoggerFactory.getLogger(IpPortSpliter.class);
	private static final String actionName = "IP端口拆分器";

	/**
	 * 拆分ip和端口成为独立的变量
	 *
	 * @param ipPortString
	 *            格式: 'ip1:port1,ip2:port2,...' 或者 'ip1,ip2:port2,...'
	 * @param defaultPort
	 *            缺省端口：当参数字符串中没有包含端口就用缺省端口填充
	 * @return
	 */
	public static List<IpPort> split(String ipPortString, int defaultPort) {
		if (StringUtils.isEmpty(ipPortString)) {
			return Collections.emptyList();
		}

		List<IpPort> ipPorts = new LinkedList<>();
		String[] split = ipPortString.split("\\s*,\\s*");
		for (String oneHost : split) {
			String[] hostPort = oneHost.split("\\s*:\\s*");
			try {
				ipPorts.add(new IpPort(hostPort[0], hostPort.length >= 2 ? Integer.parseInt(hostPort[1]) : defaultPort));
			} catch (NumberFormatException e) {
				LOGGER.error(String.format("%s-拆分(%s)出错: '%s'", actionName, Arrays.toString(hostPort), e.getMessage()), e);
			}
		}
		return ipPorts;
	}

	public static class IpPort {

		private String ip;
		private int port;

		public IpPort(String ip, int port) {
			this.ip = ip;
			this.port = port;
		}

		public String getIp() {
			return ip;
		}

		public void setIp(String ip) {
			this.ip = ip;
		}

		public int getPort() {
			return port;
		}

		public void setPort(int port) {
			this.port = port;
		}

		@Override
		public String toString() {
			return String.format("%s:%s", ip, port);
		}

	}

}
